<template>
  <div class="upload-container">
    <el-alert
      title="视频资源请转码为MP4文件，在上传，否则视为无效文件"
      type="warning"
      effect="dark"
      size="mini"
    />
    <el-upload
      action="#"
      :http-request="uploadResource"
      :multiple="false"
      :before-upload="beforeUpload"
      :on-success="onSuccess"
      :on-change="handleChange"
      :on-error="onError"
      :on-remove="onRemove"
      drag
    >
      <i class="el-icon-upload" />
      <div class="el-upload__text">请将资源拖入或<em>点击上传</em></div>
    </el-upload>
    <el-progress v-show="showProcess" :percentage="processLength" :stroke-width="2" />
  </div>
</template>

<script>
import { uploadResource, deleteResource } from '@/api/resource'
export default {
  data() {
    return {
      // 有token时需要添加token认证
      action: `${process.env.VUE_APP_BASE_API}/resource/upload`,
      resourceId: '',
      showProcess: '',
      processLength: ''
    }
  },
  methods: {
    uploadResource(param) {
      const formData = new FormData()
      formData.append('file', param.file)
      uploadResource(formData).then(response => {
        this.resourceId = response.msg
        console.log('文件上传成功')
        param.onSuccess()
      }).catch(response => {
        console.log('文件上传失败')
        param.onError()
      })
    },
    beforeUpload(file) {
      console.log(file)
      this.$emit('beforeUpload', file)
    },
    onSuccess(suc) {
      this.$message({
        message: '上传成功',
        type: 'success'
      })
      this.$emit('onSuccess', suc)
    },
    onError(err) {
      this.$message({
        message: '上传失败',
        type: 'error'
      })
      this.$emit('onError', err)
    },
    onRemove() {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 调用接口
        deleteResource(this.resourceId).then(response => {
        })
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleChange(file, fileList) {
      console.log(file, fileList)
      if (file.status === 'ready') {
        this.processLength = 0
        this.showProcess = true
        const interval = setInterval(() => {
          if (this.processLength >= 99) {
            clearInterval(interval)
            return
          }
          this.processLength += 1
        }, 20)
      }
      if (file.status === 'success') {
        this.processLength = 100
        this.showProcess = false
        this.processLength = 0
      }
    }
  }
}
</script>

<style>

</style>
